import cv2
import time
import os
 
def capture_face_and_save(image_path, output_path):
    # 加载图片
    image = cv2.imread(image_path)
 
    # 将图片转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 
    # 使用Haar级联分类器加载人脸检测模型
    cascade_path = './opencv/data/haarcascades_cuda/haarcascade_frontalface_default.xml'  # 根据实际模型文件路径修改
    cascade = cv2.CascadeClassifier(cascade_path)
 
    # 在灰度图像上检测人脸
    faces = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
 
    # 如果检测到人脸
    if len(faces) > 0:
        # 遍历检测到的人脸
        for i, (x, y, w, h) in enumerate(faces):
            # 截取人脸部分
            face_roi = image[y:y+h, x:x+w]
 
            # 保存截取的人脸部分
            base_name = os.path.basename(image_path)
            file_name, _ = os.path.splitext(base_name)
            output_file = f"{output_path}/{file_name}_face_{i:03d}.jpg"
            cv2.imwrite(output_file, face_roi)
 
            print(f"人脸已保存到: {output_file}")
 
    else:
        print("未检测到人脸。")
 
def main():
    # 示例调用

 with open('pic_list', 'r', encoding='utf-8') as f:
  for line in f:

     #print(line.rstrip('\n'))

     image_path = line.rstrip('\n')  # 替换为你的图片路径
     output_path = 'detected_faces'  # 替换为保存输出文件的路径
 
    # 调用人脸检测函数
     capture_face_and_save(image_path, output_path)
 
 
if __name__ == "__main__":
    main()
